//
//  ASSession+Certificate.m
//  AppleAuth
//
//  Created by 吴双 on 2023/1/23.
//

#import "ASSession+Certificate.h"
#import "ASSession+Private.h"
#import <AltSign/AltSign.h>
#import "ASCerReqEntry.h"

@implementation ASTeamSession (Certificate)

- (void)fetchCertificates:(void (^ _Nullable)(NSArray<ALTCertificate *> *_Nullable certificates, NSError *_Nullable error))completion {
    [[ALTAppleAPI sharedAPI] fetchCertificatesForTeam:self.team
                                              session:self.session
                                    completionHandler:^(NSArray<ALTCertificate *> * _Nullable certificates, NSError * _Nullable error) {
        if (certificates && self.privateDelegate) {
            for (ALTCertificate *item in certificates) {
                NSString *key = item.serialNumber;
                NSData *privateKey = [self.privateDelegate certificateDataForKey:key];
                if (!privateKey) continue;
                item.privateKey = privateKey;
            }
        }
        !completion ?: completion(certificates, error);
    }];
}

- (void)addCertificateWithMachineName:(NSString * _Nonnull)name
                            completed:(void (^ _Nullable)(ALTCertificate *_Nullable certificate, NSError *_Nullable error))completion {
    [[ALTAppleAPI sharedAPI] addCertificateWithMachineName:name
                                                    toTeam:self.team
                                                   session:self.session
                                         completionHandler:^(ALTCertificate * _Nullable certificate, NSError * _Nullable error) {
        if (certificate && self.privateDelegate) {
            [self.privateDelegate setCertificateData:certificate.privateKey forKey:certificate.serialNumber];
            [self fetchCertificates:^(NSArray<ALTCertificate *> * _Nullable certificates, NSError * _Nullable error) {
                for (ALTCertificate *item in certificates) {
                    if ([item.serialNumber isEqualToString:certificate.serialNumber]) {
                        !completion ?: completion(item, error);
                        return;
                    }
                }
                !completion ?: completion(certificate, error);
            }];
            return;
        }
        !completion ?: completion(certificate, error);
    }];
}

- (void)revokeCertificate:(ALTCertificate * _Nonnull)certificate
                completed:(void (^ _Nullable)(BOOL success, NSError *_Nullable error))completion {
    [[ALTAppleAPI sharedAPI] revokeCertificate:certificate
                                       forTeam:self.team
                                       session:self.session
                             completionHandler:completion];
}

@end
